import * as THREE from "_three@0.123.0@three";
import {BufferAttribute} from "_three@0.123.0@three";

export default class outLine {
  /**
   * 输入三维坐标将自动生成由三角面片构成的围栏
   * @param data example [{x:10,y:20,z:30}]
   * @param width 宽度
   * @param maxDistance 连线的最长长度
   */
  getOutLineGeometry(data,width,maxDistance = 0){
    let points = [];
    let uvs = [];
    for (let i=0;i<=data.length;i++){
      if (i>data.length-2){
        break;
      }
      let distance = this.computeDistance(data[i],data[i+1])
      if (!!maxDistance&&distance>8){
        continue;
      }
      let firstPoint = this.getPoint(data[i],'x',width);
      let sendPoint = this.getPoint(data[i+1],'x',width);

      //第一个三角形
      this.push(firstPoint[0],points,uvs,0,i/data.length)
      this.push(firstPoint[1],points,uvs,1,i/data.length)
      this.push(sendPoint[0],points,uvs,0,(i+1)/data.length)
      //第二个三角形
      this.push(firstPoint[1],points,uvs,1,i/data.length)
      this.push(sendPoint[0],points,uvs,0,(i+1)/data.length)
      this.push(sendPoint[1],points,uvs,1,(i+1)/data.length)
    }
    let buff=[new Float32Array(points),new Float32Array(uvs)];
    let bufferGeotry=new THREE.BufferGeometry();
    bufferGeotry.setAttribute("position",new BufferAttribute(buff[0],3));
    bufferGeotry.setAttribute("uv",new BufferAttribute(buff[1],2));
    return bufferGeotry;
  }
  computeDistance(startPoint,endPoint){
    return  Math.sqrt(Math.pow(startPoint.x-endPoint.x,2)+Math.pow(startPoint.y-endPoint.y,2)+Math.pow(startPoint.z-endPoint.z,2));
  }
  push(itemPoint,points,uvs,uvx,uvy){
    uvs.push(uvx)
    uvs.push(uvy)
    points.push(itemPoint.x)
    points.push(itemPoint.y)
    points.push(itemPoint.z)
  }
  getPoint(point,axis,width){
    let firstPoint = this.deepClone(point)
    firstPoint[axis] = firstPoint[axis] - width
    let secondPoint = this.deepClone(point)
    secondPoint[axis] = secondPoint[axis] + width;
    return [
      firstPoint,
      secondPoint
    ]
  }
  deepClone(obj) {
    let newObj = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === "object") {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = (obj && typeof obj[key] === 'object') ? deepClone(obj[key]) : obj[key];
        }
      }
    }
    return newObj
  }
}

